<?php

namespace app\api\controller\app;

use app\admin\model\Deviceorder;
use app\admin\model\Deviceorderdetail;
use app\admin\model\Deviceslot;
use app\admin\model\Goods;
use app\admin\model\Usercoin;
use app\admin\model\Usercoinout;
use app\admin\model\Usermno;
use app\admin\model\Userweixin;
use app\api\service\DeviceService;
use app\api\service\VbillService;
use app\common\controller\Api;
use function EasyWeChat\Kernel\Support\get_client_ip;

/**
 * 首页接口
 */
class Order extends Api
{
    protected $noNeedLogin = ['sxfOrderCallback'];
    protected $noNeedRight = ['*'];
    protected $relationSearch = true;


    public function addOrder()
    {
        $device_id = $this->request->param('device_id');
        $good_id = $this->request->param('good_id');
        $type = $this->request->param('type');
        $user = $this->auth->getUser();
        $deviceOrderModel = new Deviceorder();
        $deviceSlotModel = new Deviceslot();
        $goodModel = new Goods();

        $deviceModel = new \app\admin\model\Device();
        $orderDetailModel = new Deviceorderdetail();
        $userCoinModel = new Usercoin();
        $device = $deviceModel->where('device_id',$device_id)->find();
        $slot = $deviceSlotModel->where('device_id',$device_id)->where('status',1)->where('good_id',$good_id)->where('remain',">",0)->find();
        if(!$slot){
            $this->error("此产品库存不足，请联系机主");
        }
        $totalPrice = $slot['price'];
        $totalCoin = 0;

        $db = array();
        $key = "check_gold_".$user['mobile'];

        if($type == 'coin'){

            if($this->redis->get($key)){

                $this->error("用户正在提取金币 无法兑换商品");
            }
            $this->redis->set($key,1,60);

            $payCoin = $goodModel->getCoin($totalPrice);
            $dbCoin = $userCoinModel->where('user_id',$user['id'])->where('shop_id',$device['agent_id'])->find();
            $userCoin = 0;
            if($dbCoin){
                $userCoin = $dbCoin['coin'];
            }
            if($payCoin >$userCoin){
                $this->error("金币不足，无法兑换");
            }
            $totalCoin = $payCoin;

        }else{

        }
        $userMnoModel = new Usermno();
        $userMno = $userMnoModel->where('user_id',$device['agent_id'])->where('is_trade',1)->find();
        if(!$userMno) $this->error("支付商户号未配置，请联系平台运营");
        $db['device_id'] = $device_id;
        $db['order_no'] = getOrderSn();
        $db['status'] = "paying";
        $db['create_time'] = date("Y-m-d H:i");
        $db['price'] = $totalPrice;
        $db['coin'] = $totalCoin;
        $db['user_id'] = $user['id'];
        $db['agent_id'] = $device['agent_id'];
        $db['mno'] =$userMno['mno'];
        $db['sub_order_no'] = $device_id.getSubOrderNo();
        $id = $deviceOrderModel->insertGetId($db);
        if($id>0){



            $good = $goodModel->where('id',$slot['good_id'])->find();
            $detailDb = array();
            $detailDb['good_id'] = $slot['good_id'];
            $detailDb['slot'] = $slot['slot'];
            $detailDb['order_id'] = $id;
            $detailDb['order_no'] = $db['sub_order_no'];
            $detailDb['coin'] = $totalCoin;
            $detailDb['price'] = $totalPrice;
            $detailDb['device_id'] = $device_id;
            $detailDb['good_name'] = $good['name'];
            $detailDb['create_time'] = date("Y-m-d H:i");

            $detailDb['cover'] = $good['cover'];
            $orderDetailModel->insert($detailDb);

            if($totalCoin >0){
                $this->redis->rm($key);


                $info['order_no'] = $db['order_no'];
                $info['payInfo'] ="";

                $dbCoin = $userCoinModel->where('user_id',$user['id'])->where('shop_id',$device['agent_id'])->find();
                if($dbCoin){
                    $userCoinModel->where('id',$dbCoin['id'])->setDec('coin',$totalCoin);
                }
                $deviceOrderModel->where('id',$id)->update(['status'=>'payed','price'=>0]);

                $msgKey = "msg_order_" . $id;
                $isCount = $this->redis->get($msgKey);
                if (!$isCount) {
                    $deviceOrderDetailModel = new Deviceorderdetail();
                    $detail = $deviceOrderDetailModel->where('order_id',$id)->find();
                    $req = array();
                    $req['order_no'] =  $db['sub_order_no'];
                    $req['slot'] =$detail['slot'];
                    $req['device_id'] = $device_id;
                    $req['user_id'] = $user['id'];

                    error_log("-- slot---".json_encode($req));
                    $deviceService = new DeviceService();
                    $deviceService->ship($req);
                }

                $this->success('',$info);
            }else{

                $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/order/sxfOrderCallback";

                $fs = array();
//                $realPay = formatMoney($pay_price- $pay_price*0.006);
//                foreach ($listMnos as $key=>$val){
//                    //走分账
//                    $fusruleId = array();
//                    $fusruleId['mno'] = $val['mno'];
//                    $fusruleId['allotValue'] = formatMoney($val['ratio']*$realPay/100);
//                    $fs[] = $fusruleId;
//
//                }
//
//                $req['fusruleId'] = $fs;

                $userWxModel = new Userweixin();
                $wx = $userWxModel->where('user_id',$user['id'])->find();
                $req['mno'] = $userMno['mno'];
                $req['ordNo'] =  $db['order_no'];
                $req['amt'] = $totalPrice;

                $req['payType'] = "WECHAT";
                $req['payWay'] = "03";
                $req['subAppid'] = "wx763ae61820ee8dc5";
                $req['userId'] = $wx['openid'];

                $req['subject'] = "商品购买";
                $req['tradeSource'] = "01";
                $req['trmIp'] = get_client_ip();
                $req['notifyUrl'] = $url;

                $vbillService = new VbillService();
                $res = $vbillService->jsApi($req);

                error_log("===fz==".$res);
                $result = json_decode($res, true);
                $bizCode = $result['respData']['bizCode'];
                $bizMsg = $result['respData']['bizMsg'];

                if ($bizCode == '0000') {
                    $info['order_no'] = $db['order_no'];
                    $info['payInfo'] = $result['respData'];
                    $this->success('',$info);
                } else {
                    $this->error($bizMsg);
                }

            }
            $this->success('成功');

        }else{
            $this->error("生成订单失败,请联系机主");
        }
    }


    public function getList()
    {

        $user = $this->auth->getUser();

        $page = $this->request->param('page');

        $limit = 50;
        $offset = ($page - 1) * $limit;
        $where = array();
        $where['user_id'] = $user['id'];
        $deviceOrderModel  = new Deviceorder();
        $deviceOrderDetailModel = new Deviceorderdetail();
        $list = $deviceOrderModel->with(['user','device'])->where('Deviceorder.status',"<>",'paying')->where($where)->limit($offset,$limit)->order('create_time','desc')->select();
        foreach ($list as $key=>$val){
            $val['user']->hidden(['password', 'salt']);
           $goods =  $deviceOrderDetailModel->where('order_id',$val['id'])->select();
           foreach ($goods as $k=>$v){
               $goods[$k]['cover'] = cdnurl($v['cover'],true);
           }
           $list[$key]['goods'] = $goods;
           $list[$key]['status'] = $deviceOrderModel->getStatus($val['status']);
        }
        $this->success('',$list);
    }

    public function detail()
    {

        $order_no = $this->request->param('order_no');
        $orderModel = new Deviceorder();
        $order = $orderModel->where('order_no',$order_no)->find();
        if(!$order) $this->error("订单不存在");

        $deviceOrderDetailModel = new Deviceorderdetail();

        $deviceModel = new \app\admin\model\Device();

        $userModel = new \app\admin\model\User();
        $user = $userModel->where('id',$order['user_id'])->find();
        $order['username'] = $user['username'];
        $order['mobile'] = $user['mobile'];
        $goods =  $deviceOrderDetailModel->where('order_id',$order['id'])->select();
        foreach ($goods as $k=>$v){
            $goods[$k]['cover'] = cdnurl($v['cover'],true);
        }
        $device = $deviceModel->where('device_id',$order['device_id'])->find();
        $order['device'] = $device;
        $order['status'] = $orderModel->getStatus($order['status']);
        $order['goods'] = $goods;
        $this->success('',$order);

    }



    public function sxfOrderCallback()
    {
        $param = file_get_contents("php://input");

        $ret = json_decode($param, true);
        $amt = $ret['amt'];
        $out_trade_no = $ret['ordNo'];
        $transactionId = $ret['transactionId'];
        if ($ret['bizCode'] == '0000') {

            $back = array();
            $back['code'] = "success";
            $back['msg'] = "成功";
            echo json_encode($back);


            $deviceOrderModel = new Deviceorder();
            $deviceOrderDetailModel = new Deviceorderdetail();
            $order = $deviceOrderModel->where('order_no',$out_trade_no)->find();
            if($order){

                $userModel = new \app\admin\model\User();
                $user = $userModel->where('id',$order['user_id'])->find();
                $key = "check_gold_".$user['mobile'];
                $this->redis->rm($key);


                $deviceOrderModel->where('id',$order['id'])->update(['status'=>'payed','update_time'=>date("Y-m-d H:i")]);
                $deviceOrderDetailModel->where('order_id',$order['id'])->update(['status'=>'payed']);
                $msgKey = "msg_order_" . $order['id'];
                $isCount = $this->redis->get($msgKey);
                if (!$isCount) {

                    $detail = $deviceOrderDetailModel->where('order_id',$order['id'])->find();
                    $req = array();
                    $req['order_no'] = $order['sub_order_no'];
                    $req['slot'] =$detail['slot'];
                    $req['device_id'] =  $order['device_id'];
                    $req['user_id'] = $order['user_id'];
                    $deviceService = new DeviceService();
                    $deviceService->ship($req);
                }

            }



        }
    }

}
